

App.register('ContributionTypesTable', ContributionTypesTable = {
    
    init: function() {
        this.setup();
    },
    
    setup: function() {
        var self = this;
        
        App.listen('contributions_types.refresh', function() {
            window.history.go(0);
        });

        $("#contributions-table tbody").delegate('tr td.info','click',function(){
            $("#contributions-table tbody tr").removeClass("selected");

            $(this).parents('tr').addClass("selected");

            var contributions_id = $(this).data('id');

            App.notify('contributions_types.load', contributions_id);
        });


        setTimeout(function() {
            $("#contributions-table tbody tr:first td.info").click();
        }, 500);

        $("#add_btn").click(function(e) {
            e.preventDefault();
            
            App.notify("contributions_types.add");
        });

        $("#del_btn").click(function(e) {
            e.preventDefault();

            self.delete();
        });
    },
    
    selected: function() {
        var ids = [];

        $("#contributions-table tbody tr td input:checked").each(function() {
            ids.push( $(this).val() );
        });

        return ids;
    },

    delete: function() {
        var selected = this.selected();

        if( selected && selected.length == 0 ) {
            alert("Please select contribution types to delete in order to continue");
            return;
        }

        alertify.confirm("Are you sure you would like to remove these contribution types?", function (e) {
            if (e) {
                var url = $("#del_btn").attr("href");
                var params = {contribution_type_ids: selected};

                $.ajax({
                    url: url,
                    data: params,
                    type: 'post',
                    dataType: 'json',
                    success: function(response) {
                        if(response.status == 'success'){
                            $("#contributions-table tbody tr td input:checked").each(function() {
                                $(this).parents("tr").remove();
                            });
                            $("#contributions-table tbody tr:first td.info").click();
                        }
                        else{
                            alertify.error(response.message);
                        }
                    },
                    error: function(xhr) {
                        alertify.error("Failed to remove selected accounts. Please try again later");
                    }
                });
            } else {
                // user clicked "cancel"
            }
        });
    }
});

App.register('ContributionTypesDetails', ContributionTypesDetails = {
        
    init: function() {
        var self = this;
        
        self.setup();
        
        App.listen('contributions_types.load', function(contributions_id) {
            self.load(contributions_id);
        });
    },

    setup: function() {
        $("#contributions_view #edit_btn").click(function() {
            var contributions_id = $("#contributions-table tbody tr.selected td.info").data('id');

            App.notify('contributions_types.edit', contributions_id);
        }).css({visibility: 'visible'});
    },

    load: function(contributions_id) {

        $("#contributions_view #edit_btn").css({visibility: 'visible'});

        var url = $("#contribution_types_url").val() + "/details/" + contributions_id;

        $("#contributions_view .panel-body").html("<div class='wrapper-lg text-center'><h4>Loading Profile. Please wait ...</h4></div>");

        $.ajax({
            url: url,
            type: 'post',
            success: function(res) {
                $("#contributions_view .panel-body").html(res);
            },
            error: function(xhr) {
                $("#contributions_view .panel-body").html("<div class='wrapper-lg text-center'><h4>An Error Occured Whiles Loading Profile To View</h4></div>");
            }
        });
    }
});

App.register("ContributionsTypeEditor", ContributionsTypeEditor = {
    
    contributions_id: null,
    
    init: function() {
        var self = this;
        
        App.listen('contributions_types.add', function() {
            $("#contributions-table tbody tr").removeClass("selected");
            self.load();
        });
        
        App.listen('contributions_types.edit', function(contributions_id) {
            self.load(contributions_id);
        });
    },
    
    load: function(contributions_id) {
        var self = this;

        var url = $("#contribution_types_url").val()+"/add_edit";
        var params = {};

        if( contributions_id ) {
            url += "/" + contributions_id;
        }
        
        // always cache the contributions_id even if null
        self.contributions_id = contributions_id;

        $("#contributions_view .panel-body").html("<div class='wrapper-lg'><h4>Loading Profile. Please wait ...</h4></div>");

        $.ajax({
            url: url,
            data: params,
            type: 'post',
            success: function(res) {
                $("#contributions_view .panel-body").html(res);
                self.configure();
            },
            error: function(xhr) {
                $("#contributions_view .panel-body").html("<div class='wrapper-lg'><h3>An Error Occured Whiles Loading Profile To View</h3><div class='muted'>" + xhr.responseText + "</div></div>");
            }
        });
    },

    configure: function() {
        var self = this;

        if( $("#contributions_view #contributions_id").val() == "" ) {
            $("#contributions_view #contributions_name").friendurl({id: 'contributions_slug'});
        }
        
        $("#contributions_view #edit_btn").css({visibility: 'hidden'});

        $("#contributions_view #cancel-btn").click(function(e) {
            e.preventDefault();
            $("#contributions-table tbody tr.selected td.info").click();
        });

        $("#contributions_view form").submit(function(e) {
            e.preventDefault();

            self.save();
        });
    },

    animate_save:function(animate){
        var self = this;
        if(typeof animate == 'undefined'){
            animate = true;
        }

        if(animate){
            $('#name').attr('disabled','disabled');
            $('#description').attr('disabled','disabled');
            $('#form_actions_btn').hide();
            $('#form_loader').show();
        }
        else{
            $('#name').removeAttr('disabled');
            $('#description').removeAttr('disabled');
            $('#form_actions_btn').show();
            $('#form_loader').hide();
        }
    },

    save: function() {
        var self = this;

        var url = $("#contributions_view form").attr('action');
        var params = $("#contributions_view form").serialize();

        self.animate_save(true);

        $.ajax({
            url: url,
            data: params,
            type: 'post',
            dataType: 'json',
            success: function(res) {
                self.animate_save(false);
                if( typeof res['status'] != "undefined" ) {
                    if( res['status'] == 'success' ) {
                        if( self.contributions_id ) {
                            App.notify('contributions_types.load', self.contributions_id);
                            self.post_save('old',res);
                        }
                        else {
                            //App.notify('contributions_types.refresh');
                            alertify.success(res['message']);
                            self.post_save('new',res);
                        }
                    }
                    else {
                        alertify.error(res['message']);
                    }
                }
                else {
                    alert(JSON.stringify(res));
                }
            },
            error: function() {
                alertify.error("Failed to save changes to contributions.");
            }
        });
    },

    post_save:function(type,res){
        var self = this;
        var data = res.data;
        if(type == 'new'){
            $("#contributions-table tbody tr").removeClass("selected");
            var tr = $('<tr />').attr('data-id',data.id).addClass("selected");
            var td = $('<td />');
            var checkbox = $('<input />').attr('type','checkbox').val(data.id);
            td.append(checkbox);
            tr.append(td);
            var td = $('<td />').addClass('info').attr('data-id',data.id).html(data.name);
            tr.append(td);
            $('#contributions-table tbody').append(tr);
            App.notify('contributions_types.load', data.id);
        }
        else{
            var tr = $("tr[data-id='" + data.id + "']");
            tr.find("td:nth-child(2)").html(data.name);
        }

    }
});

